package cn.gene.timeyan.chat.config;

import cn.gene.timeyan.chat.pojo.DataVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息处理类*
 *
 * @author LWG
 * @date 2022/8/14 19:14
 * @since 1.0.0 @gene.cn
 */
public class MyHandler extends AbstractWebSocketHandler {
    private static int onlineCount = 0;
    //    线程安全
    private static Map<String, WebSocketSession> userMap = new ConcurrentHashMap<>(); // 用户
    private static Map<String, WebSocketSession> adminMap = new ConcurrentHashMap<>(); // 客服

    /**
     * @Description: 连接成功之后
     * @param session
     * @return void
     * @Author Mr.Fang
     * @date 2021/11/14 13:15
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {
        addOnlineCount(); // 当前用户加 1
        System.out.println(session.getId());
        Map<String, Object> map = session.getAttributes();
        Object token = map.get("token");
        Object admin = map.get("admin");
        DataVo dataVo = new DataVo();
        dataVo.setCode(9001).setMsg("连接成功");
        if (Objects.nonNull(admin)) {
            adminMap.put(session.getId(), session); // 添加客服
        } else  {
            //        分配客服
            userMap.put(session.getId(), session); // 添加当前用户
            distribution(dataVo);
        }
        dataVo.setId(session.getId());
        System.out.println("用户连接成功:" + admin);
        System.out.println("用户连接成功:" + token);
        System.out.println("在线用户:" + getOnlineCount());
        this.sendMsg(session, JSONObject.toJSONString(dataVo));
    }

    /**
     * @param vo
     * @return void
     * @Description: 分配客服
     * @Author Mr.Fang
     * @date 2021/11/14 13:13
     */
    private void distribution(DataVo vo) {
        if (adminMap.size() != 0) {
            Random random = new Random();
            int x = random.nextInt(adminMap.size());
            Set<String> values = adminMap.keySet();
            int j = 0;
            for (String str : values) {
                if (j == x) {
                    vo.setRecId(str);
                    System.out.println("分配ID:" + str);
                    break;
                }
                j++;
            }
        }
    }

    /**
     * @param session
     * @param message
     * @return void
     * @Description: 收发消息
     * @Author Mr.Fang
     * @date 2021/11/14 13:13
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        System.out.print("用户ID：" + session.getId());
        String payload = message.getPayload();
        System.out.println("接受到的数据:" + payload);
        DataVo dataVo = JSON.toJavaObject(JSON.parseObject(payload), DataVo.class); // json 转对象

        if (Objects.isNull(dataVo.getRecId()) || dataVo.getRecId().equals("")) { // 用户客服为空 分配客服
            WebSocketSession socketSession = adminMap.get(session.getId());
            if (Objects.isNull(socketSession)) {
                this.distribution(dataVo);
            }
        }
        if (dataVo.getCode() == 9002) {
            if (Objects.nonNull(dataVo.getRecId())) { // user -> admin
                WebSocketSession socketSession = adminMap.get(dataVo.getRecId());
                dataVo.setSelfId(session.getId()).setRecId("");
                this.sendMsg(socketSession, JSONObject.toJSONString(dataVo));
            } else if (Objects.nonNull(dataVo.getSelfId())) { // admin ->user
                WebSocketSession socketSession = userMap.get(dataVo.getSelfId());
                dataVo.setRecId(session.getId()).setSelfId("");
                this.sendMsg(socketSession, JSONObject.toJSONString(dataVo));
            }
        }
    }

    /**
     * @param session
     * @param msg
     * @return void
     * @Description: 发送消息
     * @Author Mr.Fang
     * @date 2021/11/14 13:14
     */
    private void sendMsg(WebSocketSession session, String msg) throws IOException {
        session.sendMessage(new TextMessage(msg));
    }

    /**
     * @Description: 断开连接之后
     * @param session
     * @param status
     * @return void
     * @Author Mr.Fang
     * @date 2021/11/14 13:14
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        subOnlineCount(); // 当前用户加 1
        adminMap.remove(session.getId());
        userMap.remove(session.getId());
        System.out.println("用户断开连接token:" + session.getId());
        System.out.println("用户断开连接admin:" + session.getId());
        System.out.println("在线用户:" + getOnlineCount());

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * @Description: 在线用户 +1
     * @return void
     * @Author Mr.Fang
     * @date 2021/11/14 13:16
     */
    public static synchronized void addOnlineCount() {

        MyHandler.onlineCount++;
    }

    /**
     * @Description: 在线用户 -1
     * @return void
     * @Author Mr.Fang
     * @date 2021/11/14 13:16
     */
    public static synchronized void subOnlineCount() {
        MyHandler.onlineCount--;
    }
}
